const app = getApp();
const util = require('../../utils/time.js')
const db = wx.cloud.database()
const _ = db.conmmand
Page({
  data: {
    location: null, // 位置
    index: null,
    picker: ['便民利民', '扶贫帮困', '就业指导', '治安维稳', '卫生保健', '环境维护', '宣传教育', '文体娱乐', '助农增收', '心理咨询'],
    pickerDegree: 0, // 紧急程度选择 1 紧急 2 尽快 3 正常
    imgList: [],
    imgListDone: [], // 事件处理完
    textareaAValue: '',
    textareaBValue: '',
    show: false,
    clientHeight: 557, // scroll-view 高度
    scrollTop: 0, // 距离顶部高度
  },
  // scroll-view 
  onLoad(options) {
    let that = this;
    // 动态获取scroll-view 高度
    wx.getSystemInfo({
      success: function (res) {
        let screenHeight = wx.getSystemInfoSync().windowHeight
        // console.log(screenHeight)
        let query = wx.createSelectorQuery().in(that);
        query.select('.footer_button').boundingClientRect();
        query.select('.head').boundingClientRect();
        query.exec(res => {
          // console.log(res)
          let h = res[0].height;
          let h1 = res[1].height;
          console.log(screenHeight - h - h1)
          that.setData({
            clientHeight: screenHeight - h - h1
          })
        })
      }
    })
  },
  // 上报
  save() {
    // console.log('事件内容A', this.data.textareaAValue === '')
    // console.log('图片ListA', this.data.imgList.length === 0)
    // console.log('志愿类型', this.data.picker[this.data.index] === undefined)
    // console.log('紧急程度', this.data.pickerDegree === 0)
    // console.log('地址选择', this.data.location === null)
    // console.log('处理流程', this.data.show)
    // console.log('事件内容B', this.data.textareaBValue)
    // console.log('图片ListB', this.data.imgListDone)
    var time = util.formatTime(new Date())
    if (this.data.textareaAValue != '' && this.data.imgList.length != 0 && this.data.picker[this.data.index] != undefined && this.data.pickerDegree != 0 && this.data.location != null) {
      console.log(this.data.show)
      if (!this.data.show) {
        db.collection('event').add({
          data: {
            "content": this.data.textareaAValue,
            "url": this.data.imgList,
            "index": this.data.picker[this.data.index],
            "degree": this.data.pickerDegree,
            "location": this.data.location,
            "status": this.data.show,
            user_id: app.globalData.userId,
            time:time,
          }
        })
      } else {
        db.collection('event').add({
          data: {
            "content": this.data.textareaAValue,
            "url": this.data.imgList,
            "index": this.data.picker[this.data.index],
            "degree": this.data.pickerDegree,
            "location": this.data.location,
            "status": this.data.show,
            "contentDone": this.data.textareaBValue,
            "urlDone": this.data.imgListDone,
            user_id: app.globalData.userId,
            time:time,
          }
        })
      }
      wx.showToast({
        title: '上传成功',
        icon: 'success'
      })
      setTimeout(() => {
        wx.navigateBack({
          delta: 1
        })
      }, 1000);
    } else {
      wx.showToast({
        title: '有内容未填写',
        icon: 'error'
      })
    }


  },
  // 紧急程度
  choose(e) {
    // console.log('选中',e.currentTarget.dataset.index)
    this.setData({
      pickerDegree: e.currentTarget.dataset.index
    })
  },
  // 取消按钮
  cancel() {
    wx.navigateBack({
      delta: 1,
    })
  },
  submitNotWan: function () {
    this.setData({
      show: false,
      scrollTop: 617
    })
  },
  submitWan: function () {
    this.setData({
      show: true,
      scrollTop: 1000
    })
  },
  onClickLeft() {
    wx.showToast({
      title: '点击返回',
      icon: 'none'
    });
    wx.navigateBack({
      delta: 1,
    })
  },
  PickerChange(e) {
    console.log(e);
    this.setData({
      index: e.detail.value
    })
  },
  MultiChange(e) {
    this.setData({
      multiIndex: e.detail.value
    })
  },
  TimeChange(e) {
    this.setData({
      time: e.detail.value
    })
  },
  DateChange(e) {
    this.setData({
      date: e.detail.value
    })
  },
  // 选择位置
  onChooseLocation() {
    wx.chooseLocation({
      success: (res) => {
        this.setData({
          location: res
        });
        console.log(res)
        this.setData({
          location: res
        })
      }
    });
  },
  ChooseImage() {
    wx.chooseImage({
      count: 4, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        wx.showLoading({
          title: '图片上传中...',
        })
        var time = util.formatTime(new Date()) // 获取时间
        var FilePaths = []
        const temFilePaths = res.tempFilePaths
        let promiseArr = []
        for (let i = 0; i < temFilePaths.length; i++) {
          let promise = new Promise((resolve, reject) => {
            var randstring = Math.floor(Math.random() * 1000000).toString() + '.png'
            randstring = time + '-' + randstring
            wx.cloud.uploadFile({
              cloudPath: 'orderimg/' + randstring,
              filePath: temFilePaths[i],
              success: res => {
                // get resource ID
                console.log(res.fileID)
                FilePaths[i] = res.fileID
                resolve(res)
              },
              fail: err => {
                reject(error);
              }
            })
          })
          promiseArr.push(promise)
        }
        Promise.all(promiseArr).then((result) => {
          console.log('上传图片1', FilePaths)
          if (this.data.imgList.length != 0) {
            this.setData({
              imgList: this.data.imgList.concat(FilePaths)
            })
          } else {
            this.setData({
              imgList: FilePaths
            })
          }
          wx.hideLoading()
        })
      }
    });
  },
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  ChooseImageDone() {
    wx.chooseImage({
      count: 4, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        wx.showLoading({
          title: '图片上传中...',
        })
        var time = util.formatTime(new Date()) // 获取时间
        var FilePaths = []
        const temFilePaths = res.tempFilePaths
        let promiseArr = []
        for (let i = 0; i < temFilePaths.length; i++) {
          let promise = new Promise((resolve, reject) => {
            var randstring = Math.floor(Math.random() * 1000000).toString() + '.png'
            randstring = time + '-' + randstring
            wx.cloud.uploadFile({
              cloudPath: 'orderimg/' + randstring,
              filePath: temFilePaths[i],
              success: res => {
                // get resource ID
                console.log(res.fileID)
                FilePaths[i] = res.fileID
                resolve(res)
              },
              fail: err => {
                reject(error);
              }
            })
          })
          promiseArr.push(promise)
        }
        Promise.all(promiseArr).then((result) => {
          console.log('上传图片2', FilePaths)
          if (this.data.imgListDone.length != 0) {
            this.setData({
              imgListDone: this.data.imgListDone.concat(FilePaths)
            })
          } else {
            this.setData({
              imgListDone: FilePaths
            })
          }
          wx.hideLoading()
        })
      }
    });
  },
  ViewImageDone(e) {
    wx.previewImage({
      urls: this.data.imgListDone,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(event) {
    console.log(event.currentTarget.dataset.index)
    var id = event.currentTarget.dataset.index
    var imgList = this.data.imgList
    wx.cloud.deleteFile({
      fileList: [imgList[id]]
    }).then(res => {
      imgList.splice(id, 1)
      this.setData({
        imgList: imgList
      })
      console.log(res.fileList)
    }).catch(error => {})
  },
  DelImgDone(event) {
    console.log(event.currentTarget.dataset.index)
    var id = event.currentTarget.dataset.index
    var imgListDone = this.data.imgListDone
    wx.cloud.deleteFile({
      fileList: [imgListDone[id]]
    }).then(res => {
      imgListDone.splice(id, 1)
      this.setData({
        imgListDone: imgListDone
      })
      console.log(res.fileList)
    }).catch(error => {})
  },
  textareaAInput(e) {
    this.setData({
      textareaAValue: e.detail.value
    })
  },
  textareaBInput(e) {
    this.setData({
      textareaBValue: e.detail.value
    })
  }
})